# -*- coding: utf-8 -*-
"""
   File Name:  path.py
   Author :    liccoo
   Time:       2022/8/24 12:45
"""
import os


def logs_exp(project_dir_path, args, mode):
    # 创建模型存放 logs 的父目录
    model_logs_parent_dir = os.path.join(project_dir_path, 'logs', mode, args.model, args.new_dir)
    try:
        os.makedirs(model_logs_parent_dir)
    except FileExistsError:
        # print('目录已存在')  # 调试时专用
        pass
    else:
        # print('目录创建成功')  # 调试专用
        pass

    # 创建最新的 exp 目录
    flag = 1
    num = 1
    logs_exp_dir = ''
    while flag:
        last_exp_name = f'exp{num}'  # 防止为空文件夹
        logs_exp_dir = os.path.join(model_logs_parent_dir, last_exp_name)
        try:
            os.makedirs(logs_exp_dir)
        except FileExistsError:
            num += 1
        else:
            flag = 0  # 目录创建成功，退出循环

    return logs_exp_dir


def extract_model_path(project_dir_path, model_name, exp_order, model_order, additional_path_name=''):
    # 获取指定的 exp 路径
    if exp_order == 0:
        # 遍历目录获得最后一个
        parent_logs_dir_path = os.path.join(project_dir_path, 'logs', 'train', model_name, additional_path_name)
        parent_files = os.walk(parent_logs_dir_path, topdown=False)  # 只遍历第一层子目录
        last_dir_name = ''  # 防止空文件夹时，不能遍历
        for dir_path, dir_names, filenames in parent_files:
            for dir_name in dir_names:
                last_dir_name = dir_name  # 获取到最后一个文件夹的名字
                # print(last_dir_name)  # 调试专用
        if last_dir_name == '':  # 表示这个目录下没有所需的文件
            raise FileNotFoundError("There are no required files in this directory.")
        else:
            exp_path = os.path.join(project_dir_path, 'logs', 'train', model_name, f'{last_dir_name}')
    else:
        exp_path = os.path.join(project_dir_path, 'logs', 'train', model_name, f'exp{exp_order}')

    # 获取指定的模型名称
    # 遍历所有保存的 model 文件
    flag = 0  # 判断是否存在模型文件  1 -> 存在 0 -> 不存在
    model_names = []
    for dir_path, dir_names, filenames in os.walk(exp_path, topdown=False):
        for filename in filenames:
            if filename[-3:] == '.pt':
                flag = 1
                last_filename = filename  # 获取到最后一个文件的名字
                # print(last_filename)  # 调试专用
                model_names.append(last_filename)
    # 判断是否存在模型文件，不存在就报错
    if flag == 0:
        raise FileNotFoundError('There are no required files in this directory.')
    if model_order == 0:
        model_path = os.path.join(exp_path, model_names[-1])
    else:
        model_path = os.path.join(exp_path, model_names[model_order - 1])

    # 返回指定的所存放 model 的路径
    return model_path
